#!/usr/bin python
# -*- coding: utf-8 -*-
# @Time    : 2023/6/21 16:16
# 汇总每周文件
import datetime
import os
import re
import shutil

import pymysql

from configuration_files.Connect_files import DbConnect
from create_excel import *


class SummaryCPCFile():
    def __init__(self):
        self.db = DbConnect().system_db()
        self.cursor = self.db.cursor()

    def get_date(self, beforeOfDay):
        """
        计算日期
        """
        today = datetime.datetime.now()
        offset = datetime.timedelta(days=-beforeOfDay)
        re_date = (today + offset).strftime('%Y%m%d')
        return re_date

    def get_lianxir(self, file, item):
        print("当前正在处理的文件：", file)
        """获取联系人信息"""
        info_li = file.split("_")
        item['order_number'] = info_li[1]
        item['fwr'] = info_li[0]
        item['name'] = info_li[2]
        item['sqh'] = info_li[4]
        item['inst'] = info_li[-1].strip(".pdf")
        item['type'] = "发明专利" if info_li[4][4] == "1" else "实用新型" if info_li[4][4] == "2" else "外观设计"
        if info_li[-3] == "专利申请受理通知书":
            if item['type'] == "发明专利":
                item['yjf'] = "公布印刷费50+发明专利申请实质审查费375+发明专利申请费135"
                item['money'] = "560"
                item['marks'] = "审查+实审"
            elif item['type'] == "实用新型":
                item['yjf'] = "实用新型专利申请费75"
                item['money'] = "75"
                item['marks'] = ""
            else:
                item['yjf'] = "外观设计专利申请费75"
                item['money'] = "75"
                item['marks'] = ""

        if info_li[-3] == "办理登记手续通知书":
            item['yjf'] = ""
            item['money'] = ""
            item['marks'] = ""

        if '补正' in file or '审查意见' in file or "驳回" in file:
            content = get_agentpay_content(item['sqh'])
            item = get_jf_state(content, item)  # 获取补正答复案件的缴费状态
            item = get_agent_state(item['sqh'], item)  # 获取代理人状态
            item['aj_state'] = file.split('_')[-3]

        sql = f"SELECT patent_user, liaisons, liaisons_tel, process_id, liaisons_email, user_name FROM `mykhadmin`.`orders` WHERE `order_number` = '{re.sub(r'W|F|S', '', item['order_number'])}'"
        self.cursor.execute(sql)
        data = self.cursor.fetchall()
        try:
            item['user'] = data[0][0]
            item['lxr'] = data[0][1]
            item['lxr_tel'] = data[0][2]
            item['process'] = "张倩" if data[0][3] == 58 else "杨锦" if data[0][3] == 1023 else "赵婷婷" if data[0][
                                                                                                         3] == 1085 else "徐芳" if \
                data[0][3] == 59 else "其他"
            item['email'] = data[0][4]
            item['fmr'] = data[0][5].split(",")[0]
        except:
            item['user'] = "未查到数据"
            item['lxr'] = "未查到数据"
            item['lxr_tel'] = "未查到数据"
            item['process'] = "未查到数据"
            item['email'] = ""
            item['fmr'] = ""
        return item

    def copy_dirs(self, source_path, target_path):
        """
        :param source_path: 上周待汇总CPC文件路径
        :param target_path: 新建的汇总文件夹路劲
        :return:
        """
        file_count = 0
        source_path = os.path.abspath(source_path)  # 上周带汇总CPC文件绝对路径
        target_path = os.path.abspath(target_path)  # 每周CPC汇总文件绝对路径
        if not os.path.exists(target_path):
            os.makedirs(target_path)
        st_dir, bd_dir, zs_dir, bz_dir, bh_dir = [], [], [], [], []
        if os.path.exists(source_path):
            for root, dirs, files in os.walk(source_path):
                for file in files:
                    item = {}
                    if '专利申请受理' in file or '减缴审批通知书' in file:
                        if '.pdf' in file:
                            if not os.path.exists(os.path.join(target_path, '受通费减')):
                                os.mkdir(os.path.join(target_path, '受通费减'))
                            src_file = os.path.join(root, file)
                            shutil.copy(src_file, os.path.join(target_path, '受通费减'))
                            if '专利申请受理' in file:
                                item = self.get_lianxir(file, item)  # 获取联系人
                                st_dir.append(item)
                            file_count += 1
                            continue

                    elif '办理登记手续' in file or '授权通知书' in file:
                        if '.pdf' in file:
                            if not os.path.exists(os.path.join(target_path, '办理登记')):
                                os.mkdir(os.path.join(target_path, '办理登记'))
                            src_file = os.path.join(root, file)
                            shutil.copy(src_file, os.path.join(target_path, '办理登记'))
                            if '办理登记手续' in file:
                                item = self.get_lianxir(file, item)  # 获取联系人
                                bd_dir.append(item)
                            file_count += 1
                            continue

                    elif '专利证书' in file:
                        if '.pdf' in file:
                            if not os.path.exists(os.path.join(target_path, '专利证书')):
                                os.mkdir(os.path.join(target_path, '专利证书'))
                            src_file = os.path.join(root, file)
                            shutil.copy(src_file, os.path.join(target_path, '专利证书'))
                            if '专利证书' in file:
                                item = self.get_lianxir(file, item)  # 获取联系人
                                zs_dir.append(item)
                            file_count += 1
                            continue

                    elif '补正' in file or '审查意见' in file:
                        if '.pdf' in file or '.zip' in file:
                            if not os.path.exists(os.path.join(target_path, '补正答复')):
                                os.mkdir(os.path.join(target_path, '补正答复'))
                            src_file = os.path.join(root, file)
                            shutil.copy(src_file, os.path.join(target_path, '补正答复'))
                            item = self.get_lianxir(file, item)  # 获取联系人
                            bz_dir.append(item)
                            file_count += 1

                    elif '驳回' in file:
                        if '.pdf' in file or '.zip' in file:
                            if not os.path.exists(os.path.join(target_path, '驳回案件')):
                                os.mkdir(os.path.join(target_path, '驳回案件'))
                            src_file = os.path.join(root, file)
                            shutil.copy(src_file, os.path.join(target_path, '驳回案件'))
                            item = self.get_lianxir(file, item)  # 获取联系人
                            bh_dir.append(item)
                            file_count += 1
                            continue

                    elif '缴费通知书' in file:
                        if '.pdf' in file:
                            if not os.path.exists(os.path.join(target_path, '缴费通知')):
                                os.mkdir(os.path.join(target_path, '缴费通知'))
                            src_file = os.path.join(root, file)
                            shutil.copy(src_file, os.path.join(target_path, '缴费通知'))
                            file_count += 1
                            continue

                    elif '视为撤回' in file or '视为未提出' in file or '终止通知书' in file:
                        if '.pdf' in file:
                            if not os.path.exists(os.path.join(target_path, '异常文件')):
                                os.mkdir(os.path.join(target_path, '异常文件'))
                            src_file = os.path.join(root, file)
                            shutil.copy(src_file, os.path.join(target_path, '异常文件'))
                            file_count += 1

                    elif '手续合格通知书' in file:
                        other_file_path = os.path.join(target_path, '异常文件')
                        if not os.path.exists(other_file_path):
                            os.mkdir(other_file_path)
                        if not os.path.exists(os.path.join(other_file_path, '手续合格通知书')):
                            os.mkdir(os.path.join(other_file_path, '手续合格通知书'))
                            src_file = os.path.join(root, file)
                            shutil.copy(src_file, os.path.join(other_file_path, '手续合格通知书'))
                            file_count += 1

                    else:
                        if '.pdf' in file:
                            tzs_type = file.split('_')[3]
                            other_file_path = os.path.join(target_path, '其他文件')
                            if not os.path.exists(other_file_path):
                                os.mkdir(other_file_path)
                            if not os.path.exists(os.path.join(other_file_path, tzs_type)):
                                os.mkdir(os.path.join(other_file_path, tzs_type))
                            src_file = os.path.join(root, file)
                            shutil.copy(src_file, os.path.join(other_file_path, tzs_type))
                            file_count += 1

        return st_dir, bd_dir, zs_dir, bz_dir, bh_dir, target_path

    def get_table(self, num1, num2):
        """拼接工作文件路径"""
        today = datetime.datetime.now().strftime('%Y%m%d')
        cur_filepath_list = os.getcwd()  # 获取当前文件夹路径
        date_section = self.get_date(num2) + '~' + self.get_date(num1)  # ccy  创建汇总文件名  2022-04-11~2022-04-18
        total_st, total_bd, total_zs, total_bz, total_bh, target_path = [], [], [], [], [], ""
        for file_path in os.listdir(cur_filepath_list):
            if '~' not in file_path:
                if '2024' in file_path or '2023' in file_path or '2025' in file_path:
                    if int(self.get_date(num2)) <= int(file_path) <= int(self.get_date(num1)):
                        source_path, target_path = os.path.join(cur_filepath_list, file_path), os.path.join(
                            cur_filepath_list, date_section)
                        print("============================== 开始文件汇总 ==============================")
                        st_dir, bd_dir, zs_dir, bz_dir, bh_dir, target_path = self.copy_dirs(source_path, target_path)
                        # 列表相加
                        total_st += st_dir
                        total_bd += bd_dir
                        total_zs += zs_dir
                        total_bz += bz_dir
                        total_bh += bh_dir
        print("============================== 文件汇总完毕，开始整理汇总表格 ==============================")
        self.create_excel(total_st, total_bd, total_zs, total_bz, total_bh, target_path, today)

    def create_excel(self, total_st, total_bd, total_zs, total_bz, total_bh, target_path, today):
        """制作对应的Excel表格"""
        if total_st:
            save_st_excel(total_st, target_path, today, "受通费减")
        if total_bd:
            save_st_excel(total_bd, target_path, today, "办理登记")
        if total_zs:
            save_zs_excel(total_zs, target_path, today, "专利证书")
        if total_bz:
            save_bz_bh_excel(total_bz, target_path, today, "补正答复")
        if total_bh:
            save_bz_bh_excel(total_bh, target_path, today, "驳回案件")

    def main_func(self):
        num1, num2 = 0, 0 #当天
        # num1, num2 = 1, 7 #上一周
        # 构建字典用于数据记录
        all_item = {
            '受理通知书': {'实用': 0, '发明': 0, '外观': 0},
            '授权通知书': {'实用': 0, '发明': 0, '外观': 0},
            '专利证书': {'实用': 0, '发明': 0, '外观': 0},
            '驳回': {'实用': 0, '发明': 0, '外观': 0},
        }
        # 拼接汇总文件路径，以及文件名称
        self.get_table(num1, num2)  # 汇总后的总文件路径


if __name__ == '__main__':
    SummaryCPCFile().main_func()
    print("本周汇总完成！")
